﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using YunSpace.Application.SiteLibraryManage;
using YunSpace.Domain.Entity.SiteLibraryManage;
using YunSpace.Core;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YunSpace.Application.MiniSite;
using YunSpace.Domain.ViewModel.SiteLibraryManage;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using YunSpace.Web.Common;
using YunSpace.Domain.Entity.MiniSite;
using YunSpace.Core.Excel;
using System.Data;
using System.Collections;
using System.ComponentModel;
using YunSpace.Application.SystemManage;
using YunSpace.Domain.Entity.SystemManage;
using System.Reflection;
using Microsoft.Win32;
using YunSpace.Application.SiteMgr;

#endregion

namespace YunSpace.Web.Areas.SiteManage.Controllers
{
    public class SiteController : ControllerBase
    {
        private SiteApp siteApp = new SiteApp();
        private PhotosApp photosApp = new PhotosApp();
        private FinancialApp financialApp = new FinancialApp();
        private TheContractApp theContractApp = new TheContractApp();
        private AreaApp areaApp = new AreaApp();
        private PdfApp pdfApp = new PdfApp();

        private static readonly string _toSavePdfDirectory = AppDomain.CurrentDomain.BaseDirectory;


        public string BasePath
        {
            get
            {
                return Configs.GetValue("QINIU_OUTPUT_HTTP_PATH");
            }
        }

        [HttpGet]
        [HandlerAuthorize]
        public virtual ActionResult AddForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize]
        public virtual ActionResult AttachmentForm()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize]
        public virtual ActionResult Uploader()
        {
            return View();
        }

        /// <summary>
        /// 下载 Pdf
        /// </summary>
        /// <returns></returns>
        public ActionResult DownloadPdf(string siteId)
        {
            var guid = Guid.NewGuid().ToString("N");
            var site = siteApp.GetSite(siteId);

            var fileName = site.title + ".pdf";
            var path = $"{_toSavePdfDirectory}/PDF/{DateTime.Now:yyyyMMdd}/{guid}/";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            pdfApp.CreateSitePdf(path + fileName, Server.MapPath("~") + "/Download/Images/", siteId);

            return File(path + fileName, "text/plain", fileName);
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, string queryJson)
        {
            var operatorProvider = OperatorProvider.Provider.GetCurrent();
            var data = new
            {
                rows = siteApp.GetList(pagination, queryJson,operatorProvider.UserId),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            //string vvv = QiniuHelper.Instance.updatefile();
            return Content(data.ToJson());
        }


        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = siteApp.GetForm(keyValue);
            return Content(data.ToJson());
        }

        /// <summary>
        /// 提交表单
        /// </summary>
        /// <param name="siteEntity">表单实体</param>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitForm([ModelBinder(typeof(JsonBinder<SiteInfoOutput>))]SiteInfoOutput siteInfoOutput, string keyValue)
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            siteInfoOutput.siteEntity.state = 5;
            siteInfoOutput.siteEntity.F_SupplierId = LoginInfo.UserId;

            //场地、照片、配套设施
            if (keyValue == "SiteForm") keyValue = "";
            string f_id = siteApp.SubmitSiteForm(siteInfoOutput.siteEntity, keyValue, siteInfoOutput.PhotosList, siteInfoOutput.companionSettingEntity);

            siteInfoOutput.financialEntity.F_SiteId = f_id;
            siteInfoOutput.theContractEntity.F_SiteId = f_id;

            //财务信息
            financialApp.SubmitForm(siteInfoOutput.financialEntity, siteInfoOutput.financialEntity.F_Id);
            //场地合同
            theContractApp.SubmitForm(siteInfoOutput.theContractEntity, siteInfoOutput.theContractEntity.F_Id);

            return Success(f_id);
        }


        /// <summary>
        /// 提交表单
        /// </summary>
        /// <param name="siteEntity">表单实体</param>
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult SubmitAttachmentForm(SiteEntity siteEntity, string keyValue)
        {
            siteApp.SubmitAttachmentForm(siteEntity, keyValue);

            return Success("操作成功。");
        }


        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadAttachment()
        {
            try
            {
                if (Request.Files.Count <= 0 || Request.Files[0] == null)
                {
                    throw new Exception("File_Empty_Error");
                }

                var file = Request.Files[0];

                if (file.ContentLength > 31457280)   //30mb
                {
                    throw new Exception("File_SizeLimit_Error");
                }
                string Extension = Path.GetExtension(file.FileName); //获取扩展名
                string Date = DateTime.Now.ToString("yyyyMMdd");
                Extension = DateTime.Now.ToString("hhmmss") + Extension;
                var saveKey = string.Format("Attachment/{0}/{1}", Date, Extension);

                int FileLen = file.ContentLength;
                byte[] input = new byte[FileLen];


                using (var UpLoadStream = file.InputStream)
                {
                    UpLoadStream.Read(input, 0, FileLen);
                    UpLoadStream.Position = 0;
                    var result = QiniuHelper.Instance.HttpUploadStream(UpLoadStream, saveKey);
                    if (result.Code == 200)
                    {
                        return Json(new { data = BasePath + "/" + saveKey, path = saveKey, name = file.FileName, state = 1, msg = "上传成功" });
                    }
                    return Json(new { state = 0, msg = "上传失败，请重试" });
                }
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    msg = ex.Message
                });
            }
        }


        /// <summary>
        /// 批量上传资料
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadPathFiles(string sitename)
        {
            try
            {
                var file = Request.Files;
                //string Extension = Path.GetExtension(file.FileName); //获取扩展名
                //Extension = DateTime.Now.ToString("MM-dd") + Extension;
                var saveKey = string.Format("uploads/files/path/{0}", sitename);
                var data = false;
                for (int i = 0; i < file.Count; i++)
                {
                    int FileLen = file[i].ContentLength;
                    byte[] input = new byte[FileLen];
                    using (var UpLoadStream = file[i].InputStream)
                    {
                        UpLoadStream.Read(input, 0, FileLen);
                        UpLoadStream.Position = 0;
                        var result = QiniuHelper.Instance.HttpUploadStream(UpLoadStream, saveKey + "/" + file[i].FileName);
                        if (result.Code == 200)
                        {
                            if (sitename == "Attachment")
                            {
                                return Json(new
                                {
                                    data = BasePath + "/" + saveKey + "/" + file[i].FileName,
                                    path = saveKey + "/" + file[i].FileName,
                                    name = file[i].FileName,
                                    state = 1,
                                    msg = "上传成功"
                                });
                            }
                            data = true;
                            continue;
                        }
                        else
                        {
                            data = false;
                            break;
                        }
                    }
                }
                if (data)
                {
                    return Json(new { state = 1, msg = "提交成功" });
                }
                else
                {
                    return Json(new { state = 0, msg = "提交失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    msg = ex.Message
                });
            }
        }
        /// <summary>

        /// <summary>
        /// 删除表单
        /// </summary>
        /// <param name="keyValue">表单主键</param>
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            siteApp.DeleteForm(keyValue);

            return Success("删除成功。");
        }

        /// <summary>
        /// 获取地铁站数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetMetroItemList(string keyValue)
        {
            var data = siteApp.GetMetroItemList(keyValue);

            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取数据集合
        /// </summary>
        /// <param name="keyValue">查询条件</param>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetItemListJson()
        {
            var data = new
            {
                SiteState = siteApp.GetItemList("SiteState"),
                SiteType = siteApp.GetItemList("SiteType"),
                SecondTypes = siteApp.GetItemList("SecondTypes"),
                SiteLevel = siteApp.GetItemList("SiteLevel"),
                Category = siteApp.GetItemList("SiteCategory"),
                Siteident = siteApp.GetItemList("ident"),
                Distance = siteApp.GetItemList("Distance"),
                district = siteApp.GetItemList("district"),
                City = siteApp.GetItemList("City"),
                units = siteApp.GetItemList("units"),
                site_style = siteApp.GetItemList("site_style"),
                Facilities = siteApp.GetItemList("SiteSupportingFacilities"),
                hzms = siteApp.GetItemList("hzms"),
                htzt = siteApp.GetItemList("htzt"),
                ContractWay = siteApp.GetItemList("ContractWay"),
                payment = siteApp.GetItemList("payment"),
                InvoiceType = siteApp.GetItemList("InvoiceType"),
                Subscription_Type = siteApp.GetItemList("Subscription_Type"),
                SiteTrait = siteApp.GetItemList("SiteTrait"),
                AverageConsumer = siteApp.GetItemList("AverageConsumer"),
                StoreType = siteApp.GetItemList("StoreType"),
                GuestType = siteApp.GetItemList("GuestType"),
                ReservationWay = siteApp.GetItemList("ReservationWay"),
                //PropertyFee = siteApp.GetItemList("PropertyFee"),
                //CostWater = siteApp.GetItemList("CostWater"),
                //CostNetwork = siteApp.GetItemList("CostNetwork"),
                ServicesCost = siteApp.GetItemList("ServicesCost"),
                ActivityType = siteApp.GetItemList("ActivityType"),
                FirstActivityType = siteApp.GetItemList("FirstActivityType")
            };

            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取城市区域数据集合
        /// </summary>
        /// <param name="keyValue">查询条件</param>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetDistrictJson(string codetype, string pid)
        {
            var data = new
            {
                district = siteApp.GetItemList(codetype, pid),
            };
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAuthorize]
        public virtual ActionResult Photos()
        {
            return View();
        }

        /// <summary>
        /// 获取导出场地ID存储到session
        /// </summary>
        /// <param name="siteEntity">表单实体</param>
        [HttpPost]
        public ActionResult PostKey(string queryJson)
        {

            string key = DateTime.Now.ToString("yyyyMMddhhmmss");
            Session[key] = queryJson;

            return Success(key);
        }


        [HttpGet]
        public ActionResult ToExcel(string key)
        {
            string filePath = "";
            try
            {
                List<SiteSpaceEntity> siteSpaceList = new List<SiteSpaceEntity>();
                string queryJson = Session[key].ToString();
                siteSpaceList = siteApp.GetsSpaceList(queryJson);
                string title = "场地数据" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
                //filePath = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\";

                DataTable dt = new DataTable(typeof(SiteSpaceEntity).Name);

                dt.Columns.Add("城市");
                dt.Columns.Add("场地名称");
                dt.Columns.Add("行政区域");
                dt.Columns.Add("地址");
                dt.Columns.Add("场地介绍");
                dt.Columns.Add("商圈");
                dt.Columns.Add("商场内品牌");
                dt.Columns.Add("商场定位");
                dt.Columns.Add("商场人均消费");
                dt.Columns.Add("客群定位");
                dt.Columns.Add("平日人流量");
                dt.Columns.Add("周末人流量");
                dt.Columns.Add("空间名称");
                dt.Columns.Add("落位区域");
                dt.Columns.Add("可使用面积（平米）");
                dt.Columns.Add("所处楼层");
                dt.Columns.Add("空间层高（米）");
                dt.Columns.Add("平日市场刊例价");//读取日历周一数据，如无数据，显示无
                dt.Columns.Add("周末市场刊例价");//读取平日刊例价格/基础数据
                dt.Columns.Add("价格单位");
                dt.Columns.Add("价格是否含税");
                dt.Columns.Add("活动案例");
                dt.Columns.Add("价格备注");


                PropertyInfo[] props = typeof(SiteSpaceEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                AreaEntity areaentity = new AreaEntity();
                for (int i = 0; i < siteSpaceList.Count; i++)
                {
                    SiteSpaceEntity item = siteSpaceList[i];
                    if (!item.city_id.IsNullOrEmpty())
                    {
                        areaentity = areaApp.GetForm(item.city_id);
                        item.city_id = areaentity.F_FullName;
                    }
                    if (!item.district_id.IsNullOrEmpty())
                    {
                        areaentity = areaApp.GetForm(item.district_id);
                        item.district_id = areaentity.F_FullName;
                    }
                    if (!item.business_area.IsNullOrEmpty())
                    {
                        areaentity = areaApp.GetForm(item.business_area);
                        item.business_area = areaentity.F_FullName;
                    }
                    var values = new object[props.Length];

                    for (int j = 0; j < props.Length; j++)
                    {
                        values[j] = props[j].GetValue(item, null);
                    }
                    dt.Rows.Add(values);
                }

                NPOIExcel nPOIExcel = new NPOIExcel();
                //nPOIExcel.ToExcel(dt, title, sheetName, filePath);
                nPOIExcel.ExportWebExcel(dt,title);
                return Success("ok");
            }
            catch (Exception ex)
            {
                return Success("导出失败！请联系管理员！" + "\n " + filePath);
            }
        }



        /// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }

    }
}


